
<?php 
	
	require 'vendor/autoload.php';
	require 'NotORM.php';
	
	$pdo = new PDO('mysql:host=localhost;dbname=helloSlim', 'helloSlim', 'helloSlim');
	$db; $db = new NotORM($pdo);
	
	$app = new \Slim\Slim();
	
	
	/**
	 * get all users
	 */
	$app->get('/user', function () use ($app, $db) {
		$users = array();
		$rs = $db->user();
		
		if( $_REQUEST["email"] )
		{
			$rs = $rs->where("email", $_REQUEST["email"]);
		}
		if( $_REQUEST["password"] )
		{
			$rs = $rs->where("password", $_REQUEST["password"]);
		}
		if( $_REQUEST["companyId"] )
		{
			$rs = $rs->where("companyId", $_REQUEST["companyId"]);
		}
		foreach ( $rs as $user)
		{
			$users[] = array (
				"id" => $user["id"],
				"name" => $user["name"],
				"email" => $user["email"],
				"password" => $user["password"],
				"companyId" => $user["companyId"]
			);
		}
		$app->response()->header("Content-Type", "application/json");
		echo json_encode( $users );
	});
	
	/**
	 * get user by id
	 */
	$app->get('/user/:id', function ($id) use ($app, $db) {
		$user = $db->user()->where("id", $id)->fetch();
		$user = array (
			"id" => $user["id"],
			"name" => $user["name"],
			"email" => $user["email"],
			"password" => $user["password"],
			"companyId" => $user["companyId"]
		);
		$app->response()->header("Content-Type", "application/json");
		echo json_encode($user);
	});
	
	
	/**
	 * create user
	 */
	$app->post('/user', function () use ($app, $db) {
		$app->response()->header("Content-Type", "application/json");
		$user = json_decode( $app->request()->getBody(), true );
		$user = $db->user()->insert($user);
		$user = array (
			"id" => $user["id"],
			"name" => $user["name"],
			"email" => $user["email"],
			"password" => $user["password"],
			"companyId" => $user["companyId"]
		);
		echo json_encode($user);
	});
	
	
	/**
	 * update user
	 */
	$app->put('/user/:id', function ($id) use ($app, $db) {
		$user = json_decode( $app->request()->getBody(), true );
		$db->user("id",$id)->update($user);
		$user = array (
			"id" => $user["id"],
			"name" => $user["name"],
			"email" => $user["email"],
			"password" => $user["password"],
			"companyId" => $user["companyId"]
		);
		echo json_encode($user);
	});
	
	
	/**
	 * delete user
	 */
	$app->delete('/user/:id', function ($id) use ($app, $db) {
		$app->response()->header("Content-Type", "application/json");
		$response = $db->user("id",$id)->delete();
		echo json_encode($response);
	});
	
	$app->run();
	
?>
